package cn.fairy.service.impl;

import cn.fairy.domain.Product;
import cn.fairy.domain.PurchaseApply;
import cn.fairy.domain.Stock;
import cn.fairy.domain.StockWarning;
import cn.fairy.dto.StockDto;
import cn.fairy.enums.GlobalExceptionCode;
import cn.fairy.exception.GlobalCustomException;
import cn.fairy.feign.ProductService;
import cn.fairy.feign.PurchaseService;
import cn.fairy.mapper.StockMapper;
import cn.fairy.properties.StockProperties;
import cn.fairy.result.JSONResult;
import cn.fairy.service.IStockService;
import cn.fairy.service.IStockWarningService;
import cn.fairy.util.AssertUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author fairy
 * @since 2022-09-29
 */
@Service
public class StockServiceImpl extends ServiceImpl<StockMapper, Stock> implements IStockService {
    @Autowired
    private ProductService productService;
    @Autowired
    private StockProperties stockProperties;
    @Autowired
    private IStockWarningService stockWarningService;
    @Autowired
    private PurchaseService purchaseService;

    @Override
    public void inaoutbound(StockDto stockDto) {
        Long productId = stockDto.getProductId();
        Integer state = stockDto.getState();
        Integer count = stockDto.getCount();
        // 通过商品ID查询库存信息
        Stock stock = selectByProductId(productId);
        if(state == 0){ // 入库
            if(stock == null){ // 新增库存信息
                stock = new Stock();
                stock.setCount(count);
                stock.setProductId(productId);
                JSONResult jsonResult = productService.get(productId);
                AssertUtil.isTrue(jsonResult.isSuccess(), GlobalExceptionCode.ERROR);
                Object data = jsonResult.getData();
                String jsonStr = JSONObject.toJSONString(data);
                Product product = JSON.parseObject(jsonStr, Product.class);
                stock.setProductName(product.getProductName());
                insert(stock);
            } else{ // 修改库存量
                stock.setCount(stock.getCount() + stockDto.getCount());
                updateById(stock);
            }
        } else { // 出库
            Integer stockCount = stock.getCount();
            if(stockCount < count){ // 库存不足
                // 判断是否小于阈值
                if(stockCount < stockProperties.getThreshold()){
                    Date date = new Date();
                    StockWarning StockWarning = new StockWarning();
                    BeanUtils.copyProperties(stock, StockWarning);
                    StockWarning.setInfo(stock.getProductName() + "库存不足了，请及时采购！");
                    StockWarning.setCreateTime(date);
                    stockWarningService.insert(StockWarning);
                    PurchaseApply purchaseApply = new PurchaseApply();
                    BeanUtils.copyProperties(stock, purchaseApply);
                    purchaseApply.setCreateTime(date);
                    purchaseApply.setCount(100);
                    purchaseApply.setState(0);
                    purchaseService.saveOrUpdate(purchaseApply);
                    throw new GlobalCustomException("库存不足，出库失败！");
                }
            }else { // 库存充足
                stock.setCount(stock.getCount() - stockDto.getCount());
                updateById(stock);
                PurchaseApply purchaseApply = new PurchaseApply();
                BeanUtils.copyProperties(stock, purchaseApply);
                purchaseApply.setCreateTime(new Date());
                purchaseApply.setCount(100);
                purchaseApply.setState(0);
                purchaseService.saveOrUpdate(purchaseApply);
                throw new GlobalCustomException("库存不足，出库失败！");
            }
        }

    }

    @Override
    public List<Stock> lack() {
        Integer threshold = stockProperties.getThreshold();
        Wrapper<Stock> wrapper = new EntityWrapper<>();
        wrapper.lt("count", threshold);
        List<Stock> stocks = selectList(wrapper);
        return stocks;
    }

    private Stock selectByProductId(Long productId) {
        Wrapper<Stock> wrapper = new EntityWrapper<>();
        wrapper.eq("product_id",productId);
        return selectOne(wrapper);
    }
}
